<template>
    <div class="system-management">
        <el-card>
            <div class="section-title">系统管理</div>
            
            <el-button 
                type="primary" 
                style="margin-bottom: 16px;" 
                @click="openAddDialog"
            >
                <el-icon style="margin-right: 4px;"><Plus /></el-icon>
                新增配置
            </el-button>

            <!-- 搜索筛选区域 -->
            <div class="filter-section">
                <el-form :inline="true" :model="filterForm" class="filter-form">
                    <el-form-item label="配置名称">
                        <el-input 
                            v-model="filterForm.key" 
                            placeholder="搜索配置名称" 
                            clearable
                            style="width: 200px;"
                        />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="handleFilter">
                            <el-icon><Search /></el-icon>
                            筛选
                        </el-button>
                        <el-button @click="resetFilter">
                            <el-icon><Refresh /></el-icon>
                            重置
                        </el-button>
                    </el-form-item>
                </el-form>
            </div>

            <!-- 配置卡片区域 -->
            <div class="config-container">
                <template v-if="loading">
                    <el-skeleton :rows="3" animated style="margin: 32px 0;" />
                </template>
                <template v-else>
                    <div class="config-grid">
                        <div 
                            v-for="(config, index) in tableData" 
                            :key="config.id" 
                            class="config-card"
                        >
                            <div class="card-header">
                                <div class="card-title">
                                    <el-badge :value="(currentPage-1)*pageSize + index + 1" class="config-badge">
                                        <el-icon><Setting /></el-icon>
                                    </el-badge>
                                    <span class="config-name">{{ config.key }}</span>
                                </div>
                                <div class="card-actions">
                                    <el-button 
                                        v-if="!config.isEditing"
                                        type="primary" 
                                        size="small" 
                                        @click="startEdit(config)"
                                    >
                                        <el-icon><Edit /></el-icon>
                                        编辑
                                    </el-button>
                                    <el-button 
                                        v-else
                                        type="success" 
                                        size="small" 
                                        @click="saveConfig(config)"
                                    >
                                        <el-icon><Check /></el-icon>
                                        保存
                                    </el-button>
                                    <el-button 
                                        v-if="config.isEditing"
                                        type="info" 
                                        size="small" 
                                        @click="cancelEdit(config)"
                                    >
                                        <el-icon><Close /></el-icon>
                                        取消
                                    </el-button>
                                    <el-button 
                                        v-if="!config.isEditing"
                                        type="danger" 
                                        size="small" 
                                        @click="handleDelete(config)"
                                    >
                                        <el-icon><Delete /></el-icon>
                                        删除
                                    </el-button>
                                </div>
                            </div>
                            <div class="card-body">
                                <div class="config-item">
                                    <label>
                                        <el-icon><Document /></el-icon>
                                        配置值
                                    </label>
                                    <el-input 
                                        v-if="config.isEditing" 
                                        v-model="config.value" 
                                        class="edit-input"
                                        @keyup.esc="cancelEdit(config)"
                                        ref="configValueInput"
                                    />
                                    <el-input v-else v-model="config.value" readonly />
                                </div>
                                <div class="config-item">
                                    <label>
                                        <el-icon><InfoFilled /></el-icon>
                                        描述
                                    </label>
                                    <el-input 
                                        v-if="config.isEditing" 
                                        v-model="config.description" 
                                        class="edit-input"
                                        @keyup.esc="cancelEdit(config)"
                                    />
                                    <el-input v-else v-model="config.description" readonly />
                                </div>
                                <div class="config-item">
                                    <label>
                                        <el-icon><Calendar /></el-icon>
                                        创建时间
                                    </label>
                                    <span class="create-time">{{ getCreateTime(config) }}</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </template>
            </div>
            
            <!-- 分页区域 - 固定在底部 -->
            <div class="pagination-area">
                <el-pagination
                    :background="background"
                    layout="sizes, prev, pager, next, jumper"
                    :total="total"
                    v-model:current-page="currentPage"
                    v-model:page-size="pageSize"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :disabled="false"
                />
            </div>


        </el-card>

        <!-- 新增/编辑配置对话框 -->
        <el-dialog 
            v-model="dialogVisible" 
            :title="isEdit ? '编辑配置' : '新增配置'" 
            width="500px"
            :close-on-click-modal="false"
        >
            <el-form :model="configForm" :rules="configRules" ref="configFormRef" label-width="80px">
                <el-form-item label="配置键" prop="key">
                    <el-input v-model="configForm.key" placeholder="请输入配置键" />
                </el-form-item>
                <el-form-item label="配置值" prop="value">
                    <el-input v-model="configForm.value" placeholder="请输入配置值" />
                </el-form-item>
                <el-form-item label="描述" prop="description">
                    <el-input 
                        v-model="configForm.description" 
                        type="textarea" 
                        :rows="3"
                        placeholder="请输入配置描述"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleSaveConfig" :loading="saveLoading">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
defineOptions({
  name: 'SystemIndex'
})

import { ref, computed, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { handleApiError } from '@/utils/errorHandler'
import { 
    Plus, 
    Search, 
    Refresh, 
    Edit, 
    Delete, 
    Setting, 
    InfoFilled, 
    Calendar,
    Document,
    Check,
    Close
} from '@element-plus/icons-vue'
import { getSystemConfigList, addSystemConfig, updateSystemConfig, deleteSystemConfig } from '@/api/system'

const loading = ref(true)

// 分页相关
const currentPage = ref(1)
const pageSize = ref(9)
const total = ref(0)
const background = ref(true)

// 筛选相关
const filterForm = ref({
    key: ''
})

// 配置数据
const configList = ref([])

// 筛选后的数据
const filteredConfigList = ref([])

// 计算显示的配置列表
const tableData = computed(() => {
    const startIndex = (currentPage.value - 1) * pageSize.value
    const endIndex = startIndex + pageSize.value
    return filteredConfigList.value.slice(startIndex, endIndex)
})

// 应用筛选和分页
function applyFilters() {
    let filtered = [...configList.value]
    
    // 筛选
    if (filterForm.value.key) {
        filtered = filtered.filter(config => 
            config.key.toLowerCase().includes(filterForm.value.key.toLowerCase())
        )
    }
    
    filteredConfigList.value = filtered
    total.value = filtered.length
}

// 对话框相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const saveLoading = ref(false)
const configFormRef = ref()

const configForm = ref({
    key: '',
    value: '',
    description: ''
})

const configRules = {
    key: [
        { required: true, message: '请输入配置键', trigger: 'blur' },
        { min: 2, max: 50, message: '配置键长度在 2 到 50 个字符', trigger: 'blur' }
    ],
    value: [
        { required: true, message: '请输入配置值', trigger: 'blur' }
    ]
}

// 筛选相关函数
function handleFilter() {
    currentPage.value = 1
    applyFilters() // 前端筛选
}

function resetFilter() {
    filterForm.value.key = ''
    currentPage.value = 1
    applyFilters() // 前端筛选
}

// 获取配置列表
async function fetchConfigList(showLoading = true) {
    if (showLoading) {
        loading.value = true
    }
    try {
        const response = await getSystemConfigList({
            page: 1,
            pageSize: 1000, // 获取所有数据用于前端筛选
            configName: '' // 不传筛选条件，获取所有数据
        })
        
        // 处理不同的数据结构
        if (response && response.data) {
            if (response.data.items) {
                // 分页格式数据
                configList.value = response.data.items || []
                total.value = response.data.total || 0
            } else if (Array.isArray(response.data)) {
                // 数组格式数据
                configList.value = response.data
                total.value = response.data.length
            } else {
                // 其他格式，尝试直接使用
                configList.value = response.data || []
                total.value = response.data?.length || 0
            }
            
            // 为每个配置项初始化原始值
            configList.value.forEach(config => {
                config.originalValue = config.value
                config.originalDescription = config.description
                config.isEditing = false
            })
            
            // 初始化筛选后的数据
            filteredConfigList.value = [...configList.value]
            total.value = configList.value.length
            
            // 调试：显示第一个配置项的数据结构
            if (configList.value.length > 0) {
                console.log('API返回的配置数据结构:', configList.value[0])
            }
        } else {
            configList.value = []
            total.value = 0
        }
    } catch (error) {
        handleApiError(error)
        // 如果API调用失败，使用模拟数据避免页面空白
        configList.value = [
            {
                id: 1,
                key: 'siteName',
                value: 'Universal Admin System',
                description: '系统名称',
                createTime: '2025-07-31T06:15:55.000000Z',
                updateTime: '2025-07-31T06:43:45.000000Z',
                originalValue: 'Universal Admin System',
                originalDescription: '系统名称',
                isEditing: false
            },
            {
                id: 2,
                key: 'adminEmail',
                value: 'admin@example.com',
                description: '系统管理员联系邮箱',
                createTime: '2025-07-31T06:15:30.000000Z',
                updateTime: '2025-07-31T06:43:20.000000Z',
                originalValue: 'admin@example.com',
                originalDescription: '系统管理员联系邮箱',
                isEditing: false
            }
        ]
        total.value = configList.value.length
    } finally {
        loading.value = false
        applyFilters() // 应用筛选和分页
    }
}

// 分页处理
function handleSizeChange(size) {
    pageSize.value = size
    currentPage.value = 1
    applyFilters()
}

function handleCurrentChange(page) {
    currentPage.value = page
    applyFilters()
}

// 新增配置
function openAddDialog() {
    isEdit.value = false
    configForm.value = {
        key: '',
        value: '',
        description: ''
    }
    dialogVisible.value = true
}

// 编辑配置
function openEditDialog(config) {
    isEdit.value = true
    configForm.value = {
        id: config.id,
        key: config.key,
        value: config.value,
        description: config.description
    }
    dialogVisible.value = true
}

// 保存配置
async function handleSaveConfig() {
    try {
        await configFormRef.value.validate()
        saveLoading.value = true
        
        if (isEdit.value) {
            // 编辑模式
            await updateSystemConfig({
                id: configForm.value.id,
                key: configForm.value.key,
                value: configForm.value.value,
                description: configForm.value.description
            })
            ElMessage.success('配置更新成功')
        } else {
            // 新增模式
            await addSystemConfig({
                key: configForm.value.key,
                value: configForm.value.value,
                description: configForm.value.description
            })
            ElMessage.success('配置添加成功')
        }
        
        dialogVisible.value = false
        saveLoading.value = false
        // 重新获取数据
        await fetchConfigList(false)
    } catch (error) {
        saveLoading.value = false
        handleApiError(error)
    }
}

// 删除配置
async function handleDelete(config) {
    try {
        await ElMessageBox.confirm(
            `确定要删除配置"${config.key}"吗？`,
            '确认删除',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )
        
        await deleteSystemConfig(config.id)
        ElMessage.success('删除成功')
        // 重新获取数据
        await fetchConfigList(false)
    } catch (error) {
        // 用户取消删除
    }
}

// 开始编辑
function startEdit(config) {
    // 保存原始值，用于取消时恢复
    config.originalValue = config.value
    config.originalDescription = config.description
    config.isEditing = true
    
    // 确保输入框聚焦
    nextTick(() => {
        if (config.configValueInput) {
            config.configValueInput.focus()
        }
    })
}

// 取消编辑
function cancelEdit(config) {
    config.isEditing = false
    // 恢复原始值
    config.value = config.originalValue
    config.description = config.originalDescription
}

// 保存配置
async function saveConfig(config) {
    try {
        saveLoading.value = true
        
        // 调用API保存配置
        await updateSystemConfig(config.id, {
            value: config.value,
            description: config.description
        })
        
        config.isEditing = false
        config.originalValue = config.value
        config.originalDescription = config.description
        config.updateTime = new Date().toLocaleString('zh-CN')
        ElMessage.success('配置保存成功')
        saveLoading.value = false
        // 重新获取数据
        await fetchConfigList(false)
    } catch (error) {
        saveLoading.value = false
        handleApiError(error)
    }
}

// 获取创建时间
function getCreateTime(config) {
    let timeStr = null
    
    // 尝试获取时间字段
    if (config.createTime) {
        timeStr = config.createTime
    } else if (config.createAt) {
        timeStr = config.createAt
    } else if (config.createdAt) {
        timeStr = config.createdAt
    }
    
    if (!timeStr) {
        return 'N/A'
    }
    
    try {
        // 将ISO时间格式转换为用户友好的格式
        const date = new Date(timeStr)
        return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
            hour12: false
        })
    } catch (error) {
        // 如果转换失败，返回原始值
        return timeStr
    }
}

onMounted(() => {
    // 获取配置列表
    fetchConfigList()
})
</script>

<style scoped>
.system-management {
    padding: 20px;
    height: 100vh;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

.section-title {
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 18px;
}

/* 页面头部 */
.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.header-left {
    display: flex;
    align-items: center;
    gap: 12px;
}

.page-title {
    margin: 0;
    font-size: 20px;
    font-weight: 600;
    color: #303133;
}

.config-count {
    font-size: 14px;
    color: #909399;
    background: #f5f7fa;
    padding: 4px 8px;
    border-radius: 4px;
}

/* 筛选区域 */
.filter-section {
    margin-bottom: 20px;
    padding: 16px 20px;
    background: #f8f9fa;
    border-radius: 6px;
    border: 1px solid #e9ecef;
}

.filter-form {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
    align-items: center;
    margin: 0;
}

.filter-form .el-form-item {
    margin-bottom: 0;
    margin-right: 0;
}

/* 配置容器 */
.config-container {
    flex: 1;
    overflow-y: auto;
    min-height: 0;
    max-height: calc(100vh - 400px);
    margin-bottom: 20px;
}

.config-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 12px;
    padding: 8px 0;
}

/* 配置卡片 */
.config-card {
    background: #fff;
    border: 1px solid #e4e7ed;
    border-radius: 6px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    transition: all 0.2s ease;
    overflow: hidden;
}

.config-card:hover {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
    transform: translateY(-1px);
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 12px;
    background: #f8f9fa;
    border-bottom: 1px solid #e4e7ed;
}

.card-title {
    display: flex;
    align-items: center;
    gap: 8px;
}

.config-badge {
    display: flex;
    align-items: center;
    justify-content: center;
}

.config-name {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
}

.card-actions {
    display: flex;
    gap: 8px;
}

.card-body {
    padding: 12px;
}

.config-item {
    margin-bottom: 8px;
}

.config-item:last-child {
    margin-bottom: 0;
}

.config-item label {
    display: flex;
    align-items: center;
    gap: 4px;
    font-size: 12px;
    font-weight: 500;
    color: #606266;
    margin-bottom: 4px;
}

.config-item .el-input {
    margin-bottom: 0;
}

.create-time {
    display: block;
    font-size: 12px;
    color: #909399;
    padding: 4px 8px;
    background: #f5f7fa;
    border-radius: 3px;
    border: 1px solid #e4e7ed;
}



/* 对话框样式 */
.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    padding-top: 20px;
    border-top: 1px solid #e4e7ed;
}

/* 对话框背景颜色 */
:deep(.el-dialog) {
    background-color: #fff !important;
}

:deep(.el-dialog__body) {
    background-color: #fff !important;
}

:deep(.el-dialog__header) {
    background-color: #fff !important;
}

:deep(.el-dialog__footer) {
  background-color: #fff !important;
  border-top: none;
}

/* 响应式设计 */
@media (max-width: 1200px) {
    .config-grid {
        grid-template-columns: repeat(2, 1fr);
    }
}

@media (max-width: 768px) {
    .config-container {
        margin-left: 0; /* 移除左边距，因为侧边栏被隐藏了 */
        margin-top: 0; /* 移除顶部边距，因为主布局已经处理了 */
        padding: 10px;
    }
    
    .config-grid {
        grid-template-columns: 1fr;
    }
    
    .page-header {
        flex-direction: column;
        gap: 16px;
        align-items: flex-start;
    }
    
    .filter-form {
        flex-direction: column;
        align-items: stretch;
    }
}

@media (max-width: 480px) {
    .config-container {
        margin-left: 0;
        margin-top: 0; /* 移除顶部边距 */
        padding: 5px;
    }
}

/* 滚动条样式 */
.config-container::-webkit-scrollbar {
    width: 6px;
}

.config-container::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
}

.config-container::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;
}

.config-container::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
}

/* 筛选区域输入框样式 */
.filter-form :deep(.el-input__wrapper) {
  border: none !important;
  border-bottom: 1px solid #dcdfe6 !important;
  border-radius: 0 !important;
  box-shadow: none !important;
  background: transparent !important;
}

.filter-form :deep(.el-input__wrapper:hover) {
  border-bottom-color: #409eff !important;
}

.filter-form :deep(.el-input__wrapper.is-focus) {
  border-bottom-color: #409eff !important;
  border-bottom-width: 1px !important;
}

.filter-form :deep(.el-input__inner) {
  background: transparent !important;
  border: none !important;
  box-shadow: none !important;
}

/* 分页区域样式 */
.pagination-area {
    flex-shrink: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 12px 0;
    background: #fff;
    border-top: 1px solid #f0f0f0;
    min-height: 60px;
    width: 100%;
    position: relative;
    z-index: 10;
    margin-top: 8px;
    box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
}

/* 配置卡片网格布局 - 更新样式 */
.config-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
    gap: 20px;
    margin-bottom: 20px;
    padding-bottom: 20px;
}

.config-card {
    background: #fff;
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    padding: 20px;
    transition: all 0.3s ease;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.config-card:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    transform: translateY(-2px);
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding-bottom: 12px;
    border-bottom: 1px solid #f0f0f0;
}

.card-title {
    display: flex;
    align-items: center;
    gap: 8px;
}

.config-badge {
    margin-right: 8px;
}

.config-name {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
}

.card-actions {
    display: flex;
    gap: 8px;
}

.card-body {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.config-item {
    display: flex;
    flex-direction: column;
    gap: 6px;
}

.config-item label {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 14px;
    color: #606266;
    font-weight: 500;
}

.config-item .el-input {
    margin-top: 4px;
}

.create-time {
    font-size: 14px;
    color: #909399;
    font-family: monospace;
}

/* 编辑输入框样式 - 只有下边框线 */
.edit-input :deep(.el-input__wrapper) {
    border: none !important;
    border-bottom: 1px solid #dcdfe6 !important;
    border-radius: 0 !important;
    box-shadow: none !important;
    background: transparent !important;
}

.edit-input :deep(.el-input__wrapper:hover) {
    border-bottom-color: #409eff !important;
}

.edit-input :deep(.el-input__wrapper.is-focus) {
    border-bottom-color: #409eff !important;
    border-bottom-width: 1px !important;
}

.edit-input :deep(.el-input__inner) {
    background: transparent !important;
    border: none !important;
    box-shadow: none !important;
    text-align: center !important;
}

/* 确保编辑状态下的输入框内容居中 */
.edit-input :deep(.el-input__inner) {
    text-align: center !important;
}
</style>